package com.cmcc.shared.widget


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.shared.R
import com.cmcc.shared.SdkManager
import com.cmcc.shared.databinding.FragmentCardPassengerBinding
import com.cmcc.shared.network.NetWorkListener
import com.cmcc.shared.utils.*
import com.cmcc.shared.viewModel.SharedViewModel
import kotlinx.android.synthetic.main.widget_passenger_card.view.*


/**
 * Author: caixing
 * Date: 2019/12/3
 * Description:
 */
class PassengerCardFragment : Fragment(), NetWorkListener {

    private lateinit var viewModel: SharedViewModel
    private lateinit var binding: FragmentCardPassengerBinding

    private var isDriver = false
    private var workStatus = 0
    private var familyName: String? = null
    private var familyId: String? = null
    private var companyName: String? = null
    private var companyId: String? = null


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentCardPassengerBinding.inflate(inflater, container, false)
        viewModel = ViewModelProviders.of(this).get(SharedViewModel::class.java)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        L.e("----------------PassengerCardFragment--onViewCreated")
        SdkManager.initNetWorkListener(this)

        initEvent()
        initObserver()
    }

    override fun onResume() {
        super.onResume()
        binding.passenger.tv_end.text = when (SdkManager.getLanguage()) {
            SdkManager.LANGUAGE_ENG -> "Where do you want to go"
            SdkManager.LANGUAGE_ZH_CN -> "您想去哪儿"
            SdkManager.LANGUAGE_ZH_TW -> "您想去邊度"
            else -> "您想去邊度"
        }
    }

    private fun initEvent() {
        binding.passenger.passengerFailedLayout.clickWithTrigger {
            SdkManager.logicHandler.let { it!!.tokenExpire() }
        }

        binding.passenger.passengerSuccessLayout.clickWithTrigger {
            navigationToMain(0)
        }

        binding.passenger.setHomeClickListener(View.OnClickListener {
            navigationToMain(1)
        })

        binding.passenger.setCompanyClickListener(View.OnClickListener {
            navigationToMain(2)
        })
    }

    private fun initObserver() {
        /**
         * 监听token的变化，登录之后 会产生token
         * 当token有数据的时候 就请求卡片信息
         */
        SharedViewModel.loginToken.observe(this, Observer {
            L.d("----------passenger", "token")
            //当token  变化且不为空的时候 请求卡片信息
            it.token.let { token->
                binding.passenger.loading()
                TokenUtils.setUserToken(token)
                //请求卡片信息
                viewModel.requestCardInfo(token)
            }

        })

        viewModel.carInfo.observe(this, Observer { cardInfo ->
            L.d("----------passenger", "card")
            if (null != cardInfo)
            {
                //请求卡片成功
                binding.passenger.loadSuccess()
                isDriver = cardInfo.isDriver
                if (isDriver)
                    workStatus = cardInfo.workStatus

                familyName = cardInfo.familyName
                if (!familyName.isNullOrEmpty()) {
                    familyId = cardInfo.familyPlaceId
                    binding.passenger.setHomeVisibility(View.VISIBLE)
                    val familyIndex = cardInfo.familyName.indexOf(" ")

                    familyName = if (familyIndex > 0)
                        cardInfo.familyName.substring(
                            familyIndex,
                            cardInfo.familyName.length
                        ).trim()
                    else
                        cardInfo.familyName
                } else {
                    binding.passenger.setHomeVisibility(View.INVISIBLE)
                }

                companyName = cardInfo.companyName
                if (!companyName.isNullOrEmpty()) {
                    companyId = cardInfo.companyPlaceId
                    binding.passenger.setCompanyVisibility(View.VISIBLE)
                    val companyIndex = cardInfo.companyName.indexOf(" ")

                    companyName = if (companyIndex > 0)
                        cardInfo.companyName.substring(
                            companyIndex,
                            cardInfo.companyName.length
                        ).trim()
                    else
                        cardInfo.companyName
                } else {
                    binding.passenger.setCompanyVisibility(View.INVISIBLE)
                }
            } else {
                //请求卡片失败
                binding.passenger.loadFailed()
            }
        })
    }

    private fun navigationToMain(type: Int) {
//        val token = SpHelper.getParam(context!!, SpKeys.USER_TOKEN, "")
        val token = TokenUtils.getUserToken()
        L.d("token：$token")
        if (token.isNullOrEmpty()) {
            SdkManager.logicHandler.let {
                it!!.tokenExpire()
            }
        } else {
            if (isDriver && workStatus == 1) {
                Toast.makeText(
                    context,
                    getString(R.string.driver_on_work_tip),
                    Toast.LENGTH_LONG
                ).show()
            } else {
                var postcard = ARouter.getInstance().build("/pass/main")

                if (type != 0) {
                    postcard.withString("direction", if (type == 1) familyName else companyName)
                        .withString("placeId", if (type == 1) familyId else companyId)
                }

                postcard.navigation()
            }
        }
    }


    override fun netError() {
        //showToast(context!!, getString(R.string.net_work_error_tip))
    }

    override fun unauthorized() {
        TokenUtils.setUserToken("")
//        SpHelper.removeKey(context!!, SpKeys.USER_TOKEN)
        SdkManager.logicHandler.let { it!!.tokenExpire() }
    }


}